#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
语音控制示例

演示如何使用语音控制服务实现完整的语音交互功能
"""

import sys
import os
import time
import json

# 添加父目录到路径，以便导入服务模块
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

try:
    from services.voice_control_service import VoiceControlService
    from services.realtime_audio_capture import RealTimeAudioCapture
except ImportError as e:
    print(f"❌ 导入模块失败: {e}")
    print("请确保已安装所需依赖: pip install -r requirements.txt")
    sys.exit(1)


class VoiceControlDemo:
    """语音控制演示类"""
    
    def __init__(self):
        """初始化演示"""
        print("🎯 语音控制演示初始化...")
        
        # 自定义配置
        config = {
            "vad": {
                "volume_threshold": 0.008,  # 稍微降低音量阈值，提高灵敏度
                "silence_duration": 1.5,    # 缩短静音等待时间
                "min_speech_duration": 0.3  # 缩短最小语音时长
            },
            "asr": {
                "use_cache": True,
                "confidence_threshold": 0.3  # 降低置信度阈值
            }
        }
        
        # 创建语音控制服务
        self.voice_service = VoiceControlService(config=config)
        
        # 设置回调函数
        self.setup_callbacks()
        
        print("✅ 语音控制演示准备就绪")
    
    def setup_callbacks(self):
        """设置回调函数"""
        
        def on_speech_detected(event_type: str, vad_result: dict):
            if event_type == "start":
                print("🎤 开始录音...")
            elif event_type == "end":
                print("⏹️ 录音结束，正在处理...")
        
        def on_processing_start(audio_file: str):
            print("🔄 正在分析语音...")
        
        def on_processing_end():
            print("✅ 处理完成，请继续说话...")
        
        def on_command_result(text: str, result: dict):
            success = result.get("success", False)
            if success:
                print(f"🎉 指令执行成功!")
            else:
                print(f"❌ 指令执行失败: {result.get('message', '')}")
        
        # 设置回调
        self.voice_service.on_speech_detected = on_speech_detected
        self.voice_service.on_processing_start = on_processing_start
        self.voice_service.on_processing_end = on_processing_end
        self.voice_service.on_command_result = on_command_result
    
    def run_interactive_demo(self):
        """运行交互式演示"""
        print("\n🚀 启动语音控制交互演示")
        print("=" * 60)
        
        # 显示可用设备
        print("🎧 可用音频设备:")
        capture = RealTimeAudioCapture()
        capture.list_audio_devices()
        
        # 选择设备
        device_index = None
        try:
            device_input = input("\n请输入设备编号 (回车使用默认设备): ").strip()
            if device_input:
                device_index = int(device_input)
        except ValueError:
            print("⚠️ 无效设备编号，使用默认设备")
        
        print("\n💡 使用说明:")
        print("1. 直接对着麦克风说话")
        print("2. 说完后稍等片刻，系统会自动处理")
        print("3. 支持的指令示例:")
        print("   - '播放周杰伦的稻香'")
        print("   - '帮我写一篇小说'")
        print("   - '打开文本编辑器'")
        print("   - '创建一个文件'")
        print("4. 按 Ctrl+C 退出")
        
        input("\n按回车开始语音控制...")
        
        try:
            # 启动语音控制
            success = self.voice_service.start_voice_control(device_index)
            
            if success:
                print("\n🎤 语音控制已启动，开始说话吧!")
                
                # 主循环
                while self.voice_service.is_active:
                    time.sleep(0.1)
                    
                    # 每10秒显示一次统计信息
                    if int(time.time()) % 10 == 0:
                        stats = self.voice_service.get_session_stats()
                        if stats.get("commands_processed", 0) > 0:
                            print(f"📊 已处理 {stats['commands_processed']} 个指令")
            else:
                print("❌ 启动语音控制失败")
                
        except KeyboardInterrupt:
            print("\n👋 用户退出语音控制")
        except Exception as e:
            print(f"❌ 运行出错: {e}")
        finally:
            self.voice_service.stop_voice_control()
    
    def run_text_demo(self):
        """运行文本指令演示"""
        print("\n📝 文本指令演示")
        print("=" * 40)
        
        # 预设的测试指令
        test_commands = [
            "你好，请帮我播放音乐",
            "帮我写一篇关于春天的文章",
            "打开记事本",
            "创建一个新的文本文件",
            "暂停音乐播放"
        ]
        
        print("🧪 将测试以下指令:")
        for i, cmd in enumerate(test_commands, 1):
            print(f"  {i}. {cmd}")
        
        input("\n按回车开始测试...")
        
        for i, command in enumerate(test_commands, 1):
            print(f"\n--- 测试 {i}/{len(test_commands)}: {command} ---")
            
            try:
                result = self.voice_service.process_text_command(command)
                
                # 显示简要结果
                if result.get("success"):
                    print(f"✅ 成功: {result.get('message', '')}")
                else:
                    print(f"❌ 失败: {result.get('message', '')}")
                
            except Exception as e:
                print(f"❌ 处理失败: {e}")
            
            # 等待一下再处理下一个
            if i < len(test_commands):
                time.sleep(2)
        
        print(f"\n📊 文本指令测试完成!")
    
    def run_audio_test(self):
        """运行音频测试"""
        print("\n🎤 音频功能测试")
        print("=" * 40)
        
        capture = RealTimeAudioCapture()
        
        print("🎧 可用音频设备:")
        capture.list_audio_devices()
        
        # 选择设备
        device_index = None
        try:
            device_input = input("\n请输入设备编号 (回车使用默认设备): ").strip()
            if device_input:
                device_index = int(device_input)
        except ValueError:
            print("⚠️ 无效设备编号，使用默认设备")
        
        print("\n选择测试类型:")
        print("1. 固定时长录音测试")
        print("2. VAD语音检测测试")
        
        try:
            choice = input("请选择 (1-2): ").strip()
            
            if choice == "1":
                # 固定时长录音
                duration = float(input("录音时长(秒，默认3): ") or "3")
                print(f"\n🎤 开始录制 {duration} 秒...")
                print("请开始说话...")
                
                audio_file = capture.record_fixed_duration(duration, device_index)
                if audio_file:
                    print(f"✅ 录制成功: {audio_file}")
                    
                    # 获取文件大小
                    file_size = os.path.getsize(audio_file)
                    print(f"📁 文件大小: {file_size} 字节")
                else:
                    print("❌ 录制失败")
            
            elif choice == "2":
                # VAD测试
                print("\n🎤 VAD语音检测测试")
                print("💡 开始说话，系统会自动检测语音开始和结束")
                print("   按 Ctrl+C 退出")
                
                def on_speech_start(vad_result):
                    print(f"🟢 检测到语音开始! (音量: {vad_result['volume']:.4f})")
                
                def on_speech_end(vad_result, audio_file):
                    duration = vad_result.get('speech_duration', 0)
                    print(f"🔴 语音结束! (时长: {duration:.2f}秒, 文件: {audio_file})")
                
                capture.on_speech_start = on_speech_start
                capture.on_speech_end = on_speech_end
                
                capture.start_listening(device_index)
                
                try:
                    while True:
                        time.sleep(0.1)
                except KeyboardInterrupt:
                    print("\n👋 VAD测试结束")
                finally:
                    capture.stop_listening()
            
            else:
                print("❌ 无效选择")
        
        except Exception as e:
            print(f"❌ 音频测试失败: {e}")
        finally:
            capture.cleanup_temp_files()
    
    def show_help(self):
        """显示帮助信息"""
        print("\n📋 语音控制系统帮助")
        print("=" * 50)
        
        # 显示支持的指令
        commands = self.voice_service.get_supported_commands()
        
        print("🎯 支持的指令类型:")
        for cmd_type, info in commands.items():
            print(f"\n📂 {cmd_type}: {info['description']}")
            print(f"   动作: {', '.join(info['actions'])}")
            print(f"   参数: {', '.join(info['parameters'])}")
        
        print("\n💡 使用示例:")
        examples = [
            ("播放音乐", "你好，请帮我播放周杰伦的稻香"),
            ("AI写作", "帮我写一篇关于人工智能的小说"),
            ("打开应用", "打开文本编辑器"),
            ("文件操作", "创建一个新的文本文件叫做test.txt"),
            ("音乐控制", "暂停音乐播放")
        ]
        
        for category, example in examples:
            print(f"  {category}: '{example}'")
        
        print(f"\n⚙️ 当前配置:")
        config = self.voice_service.config
        print(f"   VAD音量阈值: {config['vad']['volume_threshold']}")
        print(f"   静音等待时间: {config['vad']['silence_duration']}秒")
        print(f"   最小语音时长: {config['vad']['min_speech_duration']}秒")
        print(f"   ASR置信度阈值: {config['asr']['confidence_threshold']}")


def main():
    """主函数"""
    print("🎯 语音控制系统演示")
    print("=" * 50)
    
    try:
        demo = VoiceControlDemo()
        
        while True:
            print("\n📋 请选择演示模式:")
            print("1. 🎤 语音控制演示 (推荐)")
            print("2. 📝 文本指令测试")
            print("3. 🔧 音频功能测试")
            print("4. 📖 查看帮助信息")
            print("5. 🚪 退出")
            
            choice = input("\n请输入选择 (1-5): ").strip()
            
            if choice == "1":
                demo.run_interactive_demo()
            elif choice == "2":
                demo.run_text_demo()
            elif choice == "3":
                demo.run_audio_test()
            elif choice == "4":
                demo.show_help()
            elif choice == "5":
                print("👋 再见!")
                break
            else:
                print("❌ 无效选择，请重新输入")
    
    except KeyboardInterrupt:
        print("\n👋 用户退出")
    except Exception as e:
        print(f"❌ 演示失败: {e}")
        import traceback
        traceback.print_exc()
    finally:
        print("🧹 清理资源...")


if __name__ == "__main__":
    main()
